package com.cyf.plc.data.local.dao

import androidx.room.*
import com.cyf.plc.model.*
import kotlinx.coroutines.flow.Flow

@Dao
interface PlcDao {

    @Transaction
    @Query("SELECT * FROM PlcFault")
    fun getFaults(): Flow<List<PlcFault>>

    @Update
    fun updateFault(plcFault: PlcFault)

    @Transaction
    @Query("SELECT * FROM PlcFloor")
    fun getFloorWithRooms(): Flow<List<FloorWithRooms>>

    @Transaction
    @Query("SELECT * FROM PlcAttribute")
    fun getPlcAttributes(): Flow<MutableList<PlcAttribute>>

    @Transaction
    @Query("SELECT * FROM PlcSubAttribute")
    fun getPlcSubAttributes(): Flow<List<PlcSubAttribute>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertRooms(plcRooms: List<PlcRoom>)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertRoom(plcRoom: PlcRoom): Long

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertFloors(plcFloors: List<PlcFloor>)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertFloor(plcFloors: PlcFloor)

    @Transaction
    @Query("SELECT COUNT(*) FROM PlcAttribute")
    fun getPlcSubAttributesCount(): Flow<Int>

    @Transaction
    @Query("SELECT * FROM PlcAttribute WHERE attributeId IN (:attributeIds)")
    fun getPlcAttributes(attributeIds: Array<String>): Flow<List<PlcAttribute>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun inertPlcAttributes(plcAttributes: List<PlcAttribute>)

    @Transaction
    @Query("SELECT * FROM PlcSubAttribute WHERE attributeId IN (:attributeIds)")
    fun getPlcSubAttributes(attributeIds: Array<String>): Flow<List<PlcSubAttribute>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun inertPlcSubAttributes(plcAttributes: List<PlcSubAttribute>)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun inertPlcSubAttribute(plcSubAttribute: PlcSubAttribute)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun inertPlcAttribute(plcAttribute: PlcAttribute)

    @Delete
    fun deleteRooms(plcRooms: List<PlcRoom>)

    @Delete
    fun deleteRoom(plcRoom: PlcRoom)

    @Delete
    fun deletePlcFloor(plcFloor: PlcFloor)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun savePlcFaults(plcFaults: ArrayList<PlcFault>)

    @Query("DELETE FROM plcfloor")
    fun clearPlcFloor()

    @Query("DELETE FROM plcroom")
    fun clearPlcRoom()

    @Query("DELETE FROM plcattribute WHERE attributeId LIKE '%panel%'")
    fun clearPlcPanelAttributes()

    @Transaction
    fun deleteAll() {
        clearPlcFloor()
        clearPlcRoom()
        clearPlcPanelAttributes()
    }
}